#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
"""
    ***********************************
    *  @filename : views.py
    *  @Author : wshu
    *  @CodeDate : 19-6-26 上午10:06
    *  @Software : PyCharm
    ***********************************
    之前一版，因固定资产考虑缺陷，重写资产模块
"""
from django.shortcuts import render,get_object_or_404
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.utils.html import escape
from django.contrib.auth.models import User

from JQSetting.views import paging

from django.http import JsonResponse

import json as serialize

from .. import models, forms
from RBAC.models import Area

import datetime
import random, time


ASSET_STATUS = {
    '0': '使用中',
    '1': '闲置中',
    '2': '已销毁',
    }

REQUEST_STATUS = {
    '0': '待审批',
    '1': '待审通过',
    '2': '审批拒绝',
    }

################################
# 资产视图
################################
@login_required
def asset_view(request):
    area = Area.objects.filter(parent__isnull=True)
    asset_type = models.AssetType.objects.filter(parent__isnull=True)
    return render(request, 'AssetManage/assetlist.html', dict(area=area, asset_type=asset_type))

################################
# 资产列表
################################
@login_required
@csrf_protect
def asset_list(request):
    user = request.user
    resultdict = {}
    page = request.POST.get('page')
    rows = request.POST.get('limit')

    name = request.POST.get('name')
    if not name:
        name = ''
    key = request.POST.get('key')
    if not key:
        key = ''

    asset_type = request.POST.get('type')
    if not asset_type:
        type_get = models.AssetType.objects.filter(parent__isnull=False)
    else:
        type_get = models.AssetType.objects.filter(id=asset_type)

    if user.is_superuser:
        assetlist = models.Asset.objects.filter(
            asset_name__icontains=name,
            asset_key__icontains=key,
            asset_type__in=list(type_get.values_list('id', flat=True)),
            # asset_area__in=area_get,
        ).order_by('-asset_score', '-asset_updatetime')
    else:
        assetlist = user.asset_to_user.all().order_by('-asset_score', '-asset_updatetime')
        user_child_list = user.user_parent.all()
        for user_child in user_child_list:
            child_asset_list = user_child.asset_to_user.all().order_by('-asset_score', '-asset_updatetime')
            assetlist = assetlist | child_asset_list
        assetlist.filter(
            asset_name__icontains=name,
            asset_key__icontains=key,
            asset_type__in=type_get,
        )
    total = assetlist.count()
    assetlist = paging(assetlist, rows, page)
    data = []
    for asset_item in assetlist:
        dic = {}
        dic['asset_id'] = escape(asset_item.asset_id)
        dic['asset_name'] = escape(asset_item.asset_name)
        dic['asset_key'] = escape(asset_item.asset_key)
        dic['asset_status'] = escape(ASSET_STATUS[asset_item.asset_status])
        if asset_item.asset_inuse:
            dic['asset_inuse'] = escape('已认领')
        else:
            dic['asset_inuse'] = escape('待认领')
        if asset_item.asset_type:
            dic['asset_type'] = escape(asset_item.asset_type.name)
        else:
            dic['asset_type'] = escape('未分类')
        dic['user_email'] = escape(asset_item.user_email)
        dic['asset_score'] = escape(asset_item.asset_score)
        dic['asset_updatetime'] = escape(asset_item.asset_updatetime)
        data.append(dic)
    resultdict['code'] = 0
    resultdict['msg'] = "用户列表"
    resultdict['count'] = total
    resultdict['data'] = data
    return JsonResponse(resultdict)

################################
# 新建资产
################################
@login_required
@csrf_protect
def asset_create(request):
    user = request.user
    error = ''

    if request.method == 'POST':
        form = forms.CreateAssetForm(request.POST)
        if form.is_valid():
            try:
                num_id = models.Asset.objects.latest('id').id
            except Exception:
                num_id = 0
            num_id += 1
            asset_id = '01' + time.strftime('%Y%m%d', time.localtime(time.time())) + str(num_id)
            asset_name = form.cleaned_data['asset_name']
            asset_type = form.cleaned_data['asset_type']
            asset_key = form.cleaned_data['asset_key']
            asset_area = form.cleaned_data['asset_area']
            user_email = form.cleaned_data['user_email']
            asset_out_id = form.cleaned_data['asset_out_id']
            asset_description = form.cleaned_data['asset_description']
            asset_create = models.Asset.objects.get_or_create(
                asset_id=asset_id,
                asset_name=asset_name,
                asset_type=asset_type,
                asset_key=asset_key,
                asset_area=asset_area,
                asset_out_id=asset_out_id,
                asset_description=asset_description
            )
            if asset_create[1]:
                asset = asset_create[0]
                if user.is_superuser:
                    asset.user_email = user_email
                    user_get = User.objects.filter(email=user_email).first()
                    if user_get:
                        asset.asset_inuse = True
                        asset.asset_user.add(user)
                    else:
                        asset.asset_inuse = False
                else:
                    asset.asset_inuse = True
                    if user_email:
                        asset.user_email = user_email
                    else:
                        asset.user_email = user_email
                    asset.asset_user.add(user)
                asset.save()
            error = '添加成功'
        else:
            error = '输入不符合要求或资产已经存在，请进行资产申请'
        return render(request, 'formEdit.html', dict(form=form, post_url='assetcreate', error=error))
    else:
        form = forms.CreateAssetForm()
        return render(request, 'formEdit.html', dict(form=form, post_url='assetcreate'))

################################
# 删除资产
################################
@login_required
@csrf_protect
def assetdelete(request):
    user = request.user
    error = ''

    asset_id_list = request.POST.get('asset_id_list')
    asset_id_list = serialize.loads(asset_id_list)
    action = request.POST.get('action')
    if action == 'delete':
        for asset_id in asset_id_list:
            if user.is_superuser:
                asset = get_object_or_404(models.Asset, asset_id=asset_id)
                asset.asset_status = '2'
            else:
                asset = get_object_or_404(models.Asset, asset_user=user, asset_id=asset_id)
                asset.asset_inuse = False
                asset.asset_user.remove(user)
            asset.save()
        error = '操作成功'
    else:
        error = '参数错误'
    return JsonResponse(dict(error=error))

################################
# 更新资产
################################
@login_required
@csrf_protect
def assetupdate(request, asset_id):
    user = request.user
    error = ''
    if user.is_superuser:
        asset = get_object_or_404(models.Asset, asset_id=asset_id)
    else:
        asset = get_object_or_404(models.Asset, asset_user=user, asset_id=asset_id)
    if request.method == 'POST':
        form = forms.CreateAssetForm(request.POST,instance=asset)
        if form.is_valid():
            form.save()
            error = '修改成功'
        else:
            error = '请检查输入'
    else:
        form = forms.CreateAssetForm(instance=asset)
    return render(request,'formUpdate.html', dict(form=form, post_url='assetupdate', argu=asset_id, error=error))

################################
# 申请资产
###############################
@login_required
@csrf_protect
def asset_request(request):
    user = request.user
    error = ''
    if request.method == 'POST':
        form = forms.AssetRequest_edit_form(request.POST)
        if form.is_valid():
            asset_key= form.cleaned_data['asset_key']
            asset = models.Asset.objects.filter(asset_key=asset_key)
            if asset:
                asset_type = form.cleaned_data['asset_type']
                request_action = form.cleaned_data['request_action']
                request_reason = form.cleaned_data['request_reason']
                asset_request = models.AssetRequest.objects.get_or_create(
                    asset_key=asset_key,
                    asset_type=asset_type,
                    request_action=request_action,
                    request_reason=request_reason,
                    request_user=user
                    )
                error = '申请已提交，请等待审批'
            else:
                error = '资产库内无该资产，请使用资产新增'
        else:
            error ='请检查输入'
        return render(request, 'formedit.html', {'form':form, 'post_url': 'assetrequest','error':error})
    else:
        form = forms.AssetRequest_edit_form()
    return render(request,'formedit.html', {'form':form, 'post_url': 'assetrequest'})